<?php


namespace app\api\controller\v28;


use app\aliyun\controller\AliyunFilterWord;
use app\api\controller\v2\Auth;
use app\common\cachemodel\ZlPosterShareActive;
use app\common\cachemodel\ZlPosterShareActiveReport;
use app\common\cachemodel\ZlPosterShareActiveZanRecord;
use think\Env;
use think\response\Json;
use XznsTools\cache\CacheManage;

class PosterSheareActive extends Auth
{
    /**
     * 判断是否参加活动
     */
    public function isJoinActive()
    {
        $posterShareActiveModel = new ZlPosterShareActive();

        $weekNum = $posterShareActiveModel->getActiveWeekNum();

        $posterId = $posterShareActiveModel->getNowWeekPosterId($this->user['id'], $weekNum);

        $status = $posterId ? 1 : 0;
        if ($posterId)
        {
            $posterInfo = $posterShareActiveModel->getInfoById($posterId, ['status']);
            if ($posterInfo && isset($posterInfo['status']) && (int)$posterInfo['status'] === 2)
            {
                $status = 2;
            }
        }

        return show(config('code.success'), '请求成功', [
            'status' => $status
        ]);
    }

    /**
     * 参与评选
     */
    public function joinActive()
    {
        $posterUrl = input('poster_url/s', '');
        $isApp = input('is_app/d', 0);

        if (empty($posterUrl))
        {
            return show(config('code.error'), '参与评选必须上传海报');
        }

        //对图片进行校验
        $ossHost = Env::get('host.photo');
        $res = AliyunFilterWord::checkImg($isApp === 1, $ossHost . $posterUrl,'yellow_map', ['porn', 'terrorism', 'ad', 'live', 'ocr']);

        if ($res['status'] === false)
        {
            return show(config('code.error'), '图片违规', ['status' => 2]);
        }
        $posterShareActiveModel = new ZlPosterShareActive();

        $weekNum = $posterShareActiveModel->getActiveWeekNum();

        $posterId = $posterShareActiveModel->getNowWeekPosterId($this->user['id'], $weekNum);

        if ($posterId)
        {   // 上传新海报进行评选
            $posterInfo = $posterShareActiveModel->getInfoById($posterId);
            if ($posterInfo && isset($posterInfo['status']) && (int)$posterInfo['status'] === 2)
            {
                return show(config('code.error'), '本期参选海报违规，不能再次参选');
            }
            // 退出当前评选
            $posterShareActiveModel->leaveActive($this->user['id'], $weekNum, $posterId);
        }

        // 上传海报参与评选
        $data = [
            'uid' => $this->user['id'],
            'poster' => $posterUrl,
            'week' => $weekNum,
            'zan' => 0,
            'create_time' => $this->request->time(),
        ];

        $res = $posterShareActiveModel->joinActive($data);
        if ($res['status'])
        {
            return show(config('code.success'), '参与评选成功', [
                'id' => $res['poster_id'],
                'nickname' => $this->user['nickname'],
                'avatar' => $this->user['avatar'],
                'poster_url' => $posterUrl,
                'zan_num' => 0,
                'is_zan' => 0,
                'status' => 1
            ]);
        } else
        {
            return show(config('code.error'), '服务异常，请稍后再试～');
        }
    }

    /**
     * 获取排行榜信息
     * @return Json
     * @throws \Exception
     */
    public function getRankingList()
    {
        $isLastWeek = input('is_last_week/d', 0);

        $posterShareActiveModel = new ZlPosterShareActive();

        $weekNum = $posterShareActiveModel->getActiveWeekNum();

        if ($isLastWeek)
        {
            if ($weekNum === 1)
            {
                // 第一期  查看上期 反空
                return show(config('code.success'), '请求成功', []);
            } else
            {
                $weekNum--;
            }
        }

        $rankingList = $posterShareActiveModel->getRankingList($weekNum);

        return show(config('code.success'), '请求成功', $rankingList);
    }

    /**
     * 退出评选
     */
    public function leaveActive()
    {
        $posterShareActiveModel = new ZlPosterShareActive();

        $weekNum = $posterShareActiveModel->getActiveWeekNum();

        $posterId = $posterShareActiveModel->getNowWeekPosterId($this->user['id'], $weekNum);

        if ($posterId)
        {
            $posterInfo = $posterShareActiveModel->getInfoById($posterId);
            if ($posterInfo && isset($posterInfo['status']) && (int)$posterInfo['status'] === 2)
            {
                return show(config('code.error'), '本期参选海报违规，操作失败');
            }

            // 退出当前评选
            $posterShareActiveModel->leaveActive($this->user['id'], $weekNum, $posterId);

            return show(config('code.success'), '退出评选成功');
        } else
        {
            return show(config('code.success'), '退出评选成功');
        }
    }

    /**
     * 投票/取消投票
     */
    public function zan()
    {
        $posterId = input('poster_id/d', 0);
        if (!$posterId)
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }
        $posterShareActiveModel = new ZlPosterShareActive();

        $posterInfo = $posterShareActiveModel->getInfoById($posterId, ['status', 'zan', 'week', 'uid', 'old_zan']);
        if (!$posterInfo || (int)$posterInfo['status'] !== 1)
        {
            return show(config('code.error'), '服务异常，海报不存在');
        }

        $res = (new ZlPosterShareActive())->zanOrCancelZan($this->user['id'], $posterId);

        if ($res['status'])
        {
            $oldZan = $posterInfo['old_zan'] ?: 0;
            if ((int)$posterInfo['uid'] === $this->user['id'])
            {
                $oldZan = $oldZan + $res['zan'];
            }
            // 投票数更新
            $posterShareActiveModel->updateData($posterId, ['zan' => $posterInfo['zan'] + $res['zan'], 'old_zan' => $oldZan], (int)$posterInfo['week']);

            return show(config('code.success'), $res['msg'], $res['data']);
        } else
        {
            return show(config('code.error'), $res['msg'], $res['data']);
        }
    }

    /**
     * 获取投票记录
     * @return Json
     * @throws \Exception
     */
    public function getZanRecord()
    {
        $page = input('page/d', 1);

        $weekNum = (new ZlPosterShareActive())->getActiveWeekNum();

        $resData = (new ZlPosterShareActiveZanRecord())->getZanRecord($this->user['id'], $weekNum, $page);

        return show(config('code.success'), '请求成功', $resData);
    }

    /**
     * 获取海报列表-投票页
     */
    public function getLists()
    {
        $limit = input('limit/d', 10);

        if ($limit < 1 || $limit > 50)
        {
            $limit = 10;
        }

        $posterShareActiveModel = new ZlPosterShareActive();

        $weekNum = $posterShareActiveModel->getActiveWeekNum();

        $isNewZan = 0;
        $myPosterId = $posterShareActiveModel->getNowWeekPosterId($this->user['id'], $weekNum);
        if ($myPosterId)
        {
            $posterInfo = $posterShareActiveModel->getInfoById($myPosterId);
            if ($posterInfo)
            {
                $oldZan = $posterInfo['old_zan'] ?? 0;
                $isNewZan = $posterInfo['zan'] > $oldZan ? 1 : 0;
            }
        }

        $resData = $posterShareActiveModel->getLists($weekNum, $this->user['id'], $limit);

        return show(config('code.success'), '请求成功', ['lists' => $resData, 'is_new_zan' => $isNewZan]);
    }

    /**
     * 举报海报
     * @return Json
     * @throws \Exception
     */
    public function report()
    {
        $cause_id = input('cause_id/d', 7);
        $poster_id = input('poster_id/d', 0);
        if (!in_array($cause_id, [1, 2, 3, 4, 5, 6, 7], true))
        {
            $cause_id = 7;
        }
        $data = (new  ZlPosterShareActive())->getInfoById($poster_id);
        if (!$data)
        {
            return show(config('code.error'), '举报异常');
        }
        (new ZlPosterShareActiveReport())->insertGetId(['uid' => $this->user['id'], 'poster_id' => $poster_id, 'cause' => $cause_id, 'status' => 0, 'create_time' => time()]);
        return show(config('code.success'), '举报成功');
    }

    /**
     * 海报已读
     */
    public function posterRead()
    {
        $posterId = input('poster_id/d', 0);

        if (!$posterId)
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }

        (new ZlPosterShareActive())->userReadPOsterIdAdd($this->user['id'], $posterId);

        return show(config('code.success'), '请求成功');
    }

    /**
     * 获取我的海报列表
     * @return Json
     * @throws \Exception
     */
    public function getMyPoster()
    {
        $page = input('page/d', 1);

        $posterShareActiveModel = new ZlPosterShareActive();

        $weekNum = $posterShareActiveModel->getActiveWeekNum();

        $data = $posterShareActiveModel->getUserJoinPosterIds($this->user['id'], $page);

        $posterInfoList = $posterShareActiveModel->batchGetInfoByIds(array_keys($data['data']));

        $rankingIndexDatas = $posterShareActiveModel->getRankingIndex($weekNum);
        $resData = [];
        foreach ($data['data'] as $posterId => $zan)
        {
            if (!isset($posterInfoList[$posterId]))
            {
                continue;
            }
            $addZan = 0; // 新增
            if ($weekNum === (int)$posterInfoList[$posterId]['week'])
            {
                // 本周
                $oldZan = (int)(($posterInfoList[$posterId]['old_zan'] ?? 0) ?: 0);
                $addZan = $posterInfoList[$posterId]['zan'] - $oldZan;
                CacheManage::getInstance()->setCacheConfig('fortune.poster_share_active', $posterId)->setCache(['old_zan' => $posterInfoList[$posterId]['zan']]);
                if ($posterInfoList[$posterId]['status'] < 2)
                {
                    $rankingDesc = $rankingIndexDatas[$posterId]['ranking_index'] > 100 ? '当前未进前100名' : "当前第{$rankingIndexDatas[$posterId]['ranking_index']}名";

                } else
                {
                    $rankingDesc = '当前图片违规';
                }
            } else
            {
                $rankingDesc = $posterInfoList[$posterId]['ranking'] > 100 ? '未进前100名' : "第{$posterInfoList[$posterId]['ranking']}名";
            }

            $resData[] = [
                'id' => (int)$posterId,
                'poster_url' => $posterInfoList[$posterId]['poster'],
                'nickname' => $posterInfoList[$posterId]['nickname'],
                'avatar' => $posterInfoList[$posterId]['avatar'],
                'zan_num' => (int)$posterInfoList[$posterId]['zan'],
                'ranking_desc' => $rankingDesc,
                'is_now_week' => $weekNum === (int)$posterInfoList[$posterId]['week'] ? 1 : 0,
                'add_zan' => $addZan,
                'prize_desc' => $weekNum !== (int)$posterInfoList[$posterId]['week'] ? $posterInfoList[$posterId]['prize_des'] : '',
                'status' => (int)$posterInfoList[$posterId]['status'],
            ];
        }

        $data['data'] = $resData;

        return show(config('code.success'), '请求成功', $data);
    }
}
